// router/index.ts
import {
  createRouter,
  createWebHistory,
  type Router,
  type RouteRecordRaw,
} from "vue-router";
import Login from "@/views/login/index.vue";
import Dashboard from "@/views/Dashboard.vue";
import FormDetail from "@/views/System/FormDetail.vue";
import { useMenuStore } from "@/store/menu";
import { menuService } from "@/utils/menuService";
import { generateRoutesFromMenu } from "@/utils/routeGenerator";
import { useTagsViewStore } from "@/store/tags";

// 静态路由（不需要权限）
export const staticRoutes: RouteRecordRaw[] = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/login",
    name: "login",
    component: Login,
    meta: { hideLayout: true, showInMenu: false },
  },
  {
    path: "/dashboard",
    name: "Dashboard",
    component: Dashboard,
    meta: { title: "控制台", icon: "House", showInMenu: true },
  },
  {
    path: "/system",
    name: "system",
    meta: {
      title: "表单管理",
      showInMenu: true,
    },
    children: [
      {
        path: "/system/formDetail",
        name: "formDetail",
        component: FormDetail,
        meta: {
          title: "表单页",
          showInMenu: true,
        },
      },
    ],
  },
];

// 创建空路由实例（先不加载动态路由）
const router = createRouter({
  history: createWebHistory(),
  routes: staticRoutes, // 初始只加载静态路由
});

// 导出一个方法用于动态添加路由
export function addDynamicRoutes(dynamicRoutes: RouteRecordRaw[]) {
  dynamicRoutes.forEach((route) => {
    if (!router.hasRoute(route.name!)) {
      router.addRoute(route); // 动态添加到根路由下
    }
  });
}

router.beforeEach(async (to, from, next) => {
  const token =
    localStorage.getItem("token") || sessionStorage.getItem("token");
  const menuStore = useMenuStore();
  const tagsViewStore = useTagsViewStore();

  if (to.path === "/login") {
    next();
  } else if (!token) {
    next("/login");
  } else {
    if (menuStore.menuList.length === 0) {
      try {
        await menuService.init();
        const menuTree = menuService.getMenuTree();
        const dynamicRoutes = generateRoutesFromMenu(menuTree);
        addDynamicRoutes(dynamicRoutes);
        menuStore.setMenuList(dynamicRoutes);
        tagsViewStore.initTags();
        next({ ...to, replace: true });
      } catch (error) {
        // 处理菜单加载失败
        next("/login");
      }
    } else {
      // ✅ menuList 已存在，说明动态路由已加载，直接放行
      next();
    }
  }
});

export default router;
